import { fetchList, fetchView, collect, approve } from './api'

export default {
  namespaced: true,
  state: () => ({
    list: [],
    total: 0,
    search_list: [],
    search_total: 0,
    article: {}
  }),
  getters: {
    list (state) {
      return state.list
    },
    total (state) {
      return state.total
    },
    search_list (state) {
      return state.search_list
    },
    search_total (state) {
      return state.search_total
    },
    article (state) {
      return state.article
    }
  },
  actions: {
    async fetchList ({ commit }, params) {
      const { search = false, ...r } = params
      const { data } = await fetchList(r)
      // console.log(data)
      commit('SET_LIST', { search, ...data })
    },
    async fetchView ({ commit }, id) {
      const { data } = await fetchView(id)
      commit('SET_ARTICLE', data)
    },
    async collect ({ commit }, id) {
      await collect(id)
      commit('CHANGE_COLLECT')
    },
    async approve ({ commit }, id) {
      await approve(id)
      commit('CHANGE_APPROVE')
    },
    clearSearch ({ commit }) {
      commit('CLEAR_SEARCH')
    }
  },
  mutations: {
    SET_LIST (state, payload) {
      const { search, data, meta } = payload
      if (search) {
        state.search_list = data
        state.search_total = meta.total
      } else {
        state.list = data
        state.total = meta.total
      }
    },
    CLEAR_SEARCH (state) {
      state.search_list = []
      state.search_total = 0
    },
    SET_ARTICLE (state, payload) {
      state.article = payload.data
    },
    CHANGE_COLLECT (state) {
      state.article.is_collect = !state.article.is_collect
    },
    CHANGE_APPROVE (state) {
      state.article.is_approve = !state.article.is_approve
    }
  }
}
